<!-- 将文件夹或文档 -->
<template>
  <el-dialog
    v-model="dialogVisible"
    width="40%"
    title="添加模板"
    @close="emits('close')"
    :draggable="true"
  >
    <div class="name">
      <el-form ref="form" label-width="auto">
        <el-form-item :label="kName">
          <el-input v-model="templateName" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="templateRemark"
            type="textarea"
            placeholder="请输入备注"
          />
        </el-form-item>
        <el-form-item label="我的模板">
          <div class="knowledgelistBox" v-loading="treeLoading">
            <el-input
              v-model="filterText"
              placeholder="请输入搜索关键词"
              prefix-icon="Search"
              class="inputBox"
            />
            <el-tree
              ref="treeRef"
              class="tree"
              :data="listData"
              show-checkbox
              highlight-current
              node-key="id"
              :props="defaultProps"
              :filter-node-method="filterNode"
              @node-click="handleNodeClick"
              @check="handleCheck"
            />
          </div>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="emits('close')">取消</el-button>
        <el-button
          type="primary"
          @click="submitMemberList"
          :loading="comfirmLoading"
        >
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { Folder, Search } from "@element-plus/icons-vue";
import { debounce, get } from "lodash-es";
import MemberAssignmentIcon from "@/assets/customIcon/MemberAssignment.vue";
// import { getFolderDetail } from "@/api/folder";

import {
  getKnowledgeList,
  getMyKnowledgeList,
  getKnowledgeInfo,
  renameKnowledge,
  topKnowledge,
  deleteKnowledge,
} from "@/api/folder";
import {
  getMyTemplateList,
  getPersonageTemplateFolder,
  getTemplateInfo,
  addPersonalTemplateFolder,
  updatePersonalTemplateFolder,
  topPersonalTemplateFolder,
  deleteTemplate,
} from "@/api/template.js";
import { getDocumentList } from "@/api/document.js";
import { getDocumentMemberList } from "@/api/document";
import { getUserList } from "@/api/account";
import { ElMessage, ElMessageBox } from "element-plus";
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  name: {
    type: String,
    default: () => {},
  },
  structure: {
    type: String,
    default: "",
  },
  callBack: {
    type: Function,
    default: () => {},
  },
});
const dialogVisible = computed({
  get() {
    return props.visible;
  },
});
const emits = defineEmits(["close"]);
const listData = ref([]);
const kName = ref("");
const templateName = ref("");
const templateRemark = ref("");

const confirmAssignLoading = ref(false);
const defaultProps = {
  children: "children",
  label: "name",
  isLeaf: "leaf",
  disabled: "disabled",
};

const handleNodeClick = (data, nodeProps, node, e) => {
  console.log(data, nodeProps, node, e);
};
// 处理顶层节点单选
const handleCheck = (data, { checkedKeys }) => {
  console.log(data, checkedKeys);
  // 如果勾选了当前节点，清除其他已选节点
  if (data.children) {
    treeRef.value.setCheckedKeys([data.id]);
  }
};
const filterText = ref("");
const treeRef = ref(null);
watch(filterText, (val) => {
  treeRef.value?.filter(val);
});
const filterNode = (value, data) => {
  if (!value) return true;
  return data.name.includes(value);
};
const comfirmLoading = ref(false);
const submitMemberList = () => {
  comfirmLoading.value = true;
  if (props.structure == "folder") {
    props
      .callBack(templateName.value, templateRemark.value)
      .then((res) => {
        ElMessage.success("添加成功");
        emits("close");
      })
      .catch((err) => {
        // 接口文件已做报错处理，这里无需处理
        // ElMessage.closeAll();
        // ElMessage.error(err);
      })
      .finally(() => {
        comfirmLoading.value = false;
      });
  } else if (props.structure == "file") {
    const checkedNodes = treeRef.value?.getCheckedNodes() || [];
    console.log(checkedNodes, "checkedNodes");
    // const folderId = checkedNodes[0]?.id;
    const folderId = checkedNodes.find((item) => item.folderName).id;
    props
      .callBack(templateName.value, templateRemark.value, folderId)
      .then((res) => {
        ElMessage.success("添加成功");
        emits("close");
      })
      .catch((err) => {
        // 接口文件已做报错处理，这里无需处理
        // ElMessage.closeAll();
        // ElMessage.error(err);
      })
      .finally(() => {
        comfirmLoading.value = false;
      });
  }
};

const loadNode = async (node, resolve) => {
  console.log(node, "node");
  if (node.level === 0) {
    return resolve(await getList());
  } else if (node.level === 1) {
    // getKnowledgeInfo(node.data.id);
    getDocumentList({
      folderId: node.data.id,
      folderName: node.data.folderName,
      delFlag: 0,
    });
    getMyKnowledgeList();
    return resolve([{ name: "成员", leaf: true }]);
  }
};

const treeLoading = ref(false);

// 处理数据
const transData = (data) => {
  return data.map((item) => {
    // 文件列表在这个字段中edPersonageTemplateDocumentVoList
    if (props.structure == "file") {
      return {
        ...item,
        name: item.folderName,
        disabled: item.delFlag == 0 ? false : true,
        children:
          item.edPersonageTemplateDocumentVoList &&
          item.edPersonageTemplateDocumentVoList.length > 0
            ? item.edPersonageTemplateDocumentVoList.map((file) => {
                return {
                  ...file,
                  name: file.fileName,
                  leaf: true,
                  disabled: file.delFlag == 0 ? false : true,
                  children: [],
                };
              })
            : [{ name: "---暂无文件---", leaf: true, disabled: true }],
      };
    } else {
      return {
        ...item,
        name: item.folderName,
        disabled: item.delFlag == 0 ? false : true,
        leaf: false,
        children: [],
      };
    }
  });
};
// 获取数据
const getList = async () => {
  treeLoading.value = true;
  return new Promise((resolve, reject) => {
    getMyTemplateList()
      .then((res) => {
        if (res.code == 200) {
          listData.value = transData(res.data);
          resolve(listData.value);
        } else {
          reject(res);
        }
      })
      .catch((err) => {
        reject(err);
      })
      .finally(() => {
        treeLoading.value = false;
      });
  });
};

onMounted(() => {
  console.log(props);
  getList();
  if (props.structure == "folder") {
    kName.value = "模板文件夹名称";
    templateName.value = props.name;
  } else if (props.structure == "file") {
    kName.value = "模板文档名称";
    templateName.value = props.name;
  }
});
</script>
<style lang="scss" scoped>
.el-dialog__title {
  display: flex;
  align-items: center;
  gap: 10px;
}
.knowledgelistBox {
  width: 100%;
  padding: 5px;
  // border: 1px solid #3c3c3c;
  box-shadow: 0 0 0 0.00521rem
    var(--el-input-border-color, var(--el-border-color)) inset;
  min-height: 200px;
  max-height: 50vh;
  display: flex;
  flex-direction: column;
  .inputBox {
    height: var(--el-input-inner-height);
    margin-bottom: 10px;
  }
  .tree {
    flex: 1;
    overflow: auto;
  }
}
</style>
<style>
.el-table .disabled-row {
  /* --el-table-tr-bg-color: var(--el-color-success-light-9); */
  color: #ccc;
}
/* 隐藏叶子节点的复选框 */
.is-leaf + .el-checkbox {
  display: none;
}
</style>
